<?php
namespace App\Http\Controllers\Api\V6;
use App\Http\Controllers\Api\V6\CompanyController;
use Illuminate\Http\Request;
use App\Models\V6\CompanyQuestionModel as QuestionModel;
use App\Models\V6\ReadPartyModel;
use App\Models\V6\MemberModel;
use DB;


class CompanyQuestionController extends CompanyController{

    /**
     * 保存图片
     * */
    private function storage_imgs(Request $request)
    {
        $imgs   = [];

        foreach($request->allFiles() as $file)
        {
            $ext        = $file->getClientOriginalExtension();
            $filePath   = "uploads/question/".date('Y')."/".date('m')."/".date('d');
            $path       = public_path($filePath);
            $fileName   = create_member_number().".".$ext;
            $filePath   = $filePath."/".$fileName;
            $file->move($path,$fileName);
            array_push($imgs,$filePath);
        }
        return $imgs;
    }

    /**
     * 添加问题
     * */
    public function add_question(Request $request)
    {
        $userId         = $request->input('userId');
        $questionType   = $request->input('questionType');
        $question       = emoji_text_encode($request->input('question'));
        $isAnonymous    = $request->input('isAnonymous');
        $readPartyId    = $request->input('readPartyId',0);

        //$imgs           = $this->storage_imgs($request);

        $imgs           = [];
        $questionModel  = new QuestionModel();
        $companyId      = 0;

        $questionModel->add_question($question,$imgs,$questionType,$userId,$companyId,$readPartyId,$isAnonymous);
        return apiData()->send(200,'ok');
    }



    /**
     * 众智共享问题列表
     *
     * */
    public function question_page(Request $request)
    {
        $showType       = $request->input('showType',0);    //0:全部 1.已解答 2.我的提问 4.按类型分类
        $userId         = $request->input('userId',0);
        $questionType   = $request->input('questionType',"");

        $questionModel  = new QuestionModel();

        $companyId      = 0;
        $isAnswered     = -1;

        switch($showType)
        {
            case 0 : $isAnswered    = -1;   $uid = 0; break;
            case 1 : $isAnswered    = 1;    $uid = 0; break;
            case 2 : $uid           = $userId;        break;
            case 3 : $uid           = 0;              break;
        }

        $questions      = $questionModel->get_questions($companyId,$uid,$isAnswered,$questionType);

        foreach($questions as $quest)
        {
            //如果已经采纳，则获取采纳内容
            if($showType == 1 || ($questionType != "" && $quest->answer_id > 0)){

                $answer = DB::table('company_question_answer')->where('id',$quest->answer_id)->first();
                $quest->answer = $answer->answer;
            }


            if(count($quest->imgs) > 0)
            {
                array_walk($quest->imgs,function(&$v,$k,$pre){$v = $pre.$v;},env('HOST')."/");
            }

            $quest->head_img    = change_member_head_img($quest->head_img);
            $quest->question    = emoji_text_decode($quest->question);
            //统计回答数量
            $answerUsers        = $questionModel->get_top_answer_user($quest->id);
            $quest->answerNumber= count($answerUsers);
            $quest->selfIsAnswered= in_array($userId,$answerUsers) ? 1 : 0;

            $quest->created_at  = fulltime_to_shorttime($quest->created_at);
        }
        return apiData()->set_data('questions',$questions)->send(200,'ok');
    }


    /**
     * 问题详情界面
     * */
    public function question_detail(Request $request)
    {
        $questionId     = $request->input('questionId');
        $userId         = $request->input('userId');
        $questionModel  = new QuestionModel();
        $questionDetail = $questionModel->get_question_detail($questionId);
        $questionDetail->created_at = fulltime_to_shorttime($questionDetail->created_at);
        $answers        = $questionModel->get_question_answer($questionId,$userId);
        $topAnswers     = [];
        $questionDetail->question   = emoji_text_decode($questionDetail->question);
        array_walk($questionDetail->imgs,function(&$v,$k,$pre){$v = $pre.$v;},env('HOST')."/");


        foreach($answers as $ans)
        {
            if(count($ans->imgs) > 0)
            {
                array_walk($ans->imgs,function(&$v,$k,$pre){$v = $pre.$v;},env('HOST')."/");
            }

            $ans->created_at = fulltime_to_shorttime($ans->created_at);
        }

        foreach($answers as $ans)
        {
            $pid    = $ans->parent_id;
            if( $pid == 0)
            {
                $ans->subAnswer = $this->get_sub_answer($answers,$ans->id);
                array_push($topAnswers,$ans);
            }
        }

        return apiData()
            ->set_data('questionInfo',$questionDetail)
            ->set_data('answers',$topAnswers)
            ->send(200,"ok");
    }


    /**
     * 添加答案
     * */
    public function add_answer(Request $request)
    {

        $userId         = $request->input('userId');
        $questionId     = $request->input('questionId');    //问题ID
        $answer         = emoji_text_encode($request->input('answer'));        //回复的内容
        $answerId       = $request->input('answerId',0);      //答案ID
        $isAnonymous    = $request->input('isAnonymous',0); //是否匿名
        $topAnswerId    = $request->input('topAnswerId',0); //最顶级的评论ID

        $replyedUserId  = 0;

        $questionModel  = new QuestionModel();

        $questionInfo   = $questionModel->get_question_detail($questionId);
        if($questionInfo->answer_id > 0)
        {
            return apiData()->send(4001,'本问题已采纳了其他回答');
        }

        $imgs           = $this->storage_imgs($request);

        if($answerId >0)
        {
            $answerInfo     = $questionModel->get_single_answer($answerId);
            $replyedUserId  = $answerInfo->user_id;
        }

        $newAnswerId    = $questionModel->add_answer($questionId,$answer,$answerId,$userId,$replyedUserId,$imgs,$isAnonymous);
        $topAnswerId    = $topAnswerId == 0 ? $newAnswerId : $topAnswerId;


        $answerInfo     = $this->single_answer($questionId,$topAnswerId);
        return apiData()->set_data('answerInfo',$answerInfo)->send(200,'ok');
    }


    /**
     * 获取单条回复信息
     * @param integer $questionId 问题ID
     * @param integer $answerId 答案ID
     * @param integer $userId   用户ID
     * */
    public function single_answer($questionId,$answerId,$userId = 0)
    {
        $questionModel  = new QuestionModel();
        $answers        = $questionModel->get_question_answer($questionId,$userId);
        foreach($answers as $ans)
        {
            if(count($ans->imgs) > 0)
            {
                array_walk($ans->imgs,function(&$v,$k,$pre){$v = $pre.$v;},env('HOST')."/");
            }
        }

        foreach($answers as $ans)
        {
            if($ans->id == $answerId)
            {
                $ans->subAnswer = $this->get_sub_answer($answers,$ans->id);
                $answers = $ans;
                break;
            }
        }
        return $answers;
    }

    /**
     * 获得子评论
     * */
    private function get_sub_answer($answers,$pid)
    {
        $ids = [$pid];
        $subAnswer = [];
        foreach($answers as $ans1)
        {
            $pid = $ans1->parent_id;
            if(in_array($pid,$ids))
            {
                $ans1->subAnswer = [];
                array_push($subAnswer,$ans1);

                array_push($ids,$ans1->id);
            }
        }

        return $subAnswer;
    }


    /**
     * 采纳答案
     * */
    public function accept_answer(Request $request)
    {
        $userId     = $request->input('userId');
        $questionId = $request->input('questionId');
        $answerId   = $request->input('answerId');

        $questionModel  = new QuestionModel();
        $questionInfo   = $questionModel->get_question_detail($questionId);

        if($questionInfo->answer_id > 0)
        {
            return apiData()->send(4001,'本问题已采纳了其他回答');
        }
        $questionModel->accept_answer($questionId,$answerId);

        return apiData()->send(200,'ok');
    }


    /**
     * 点赞答案
     * */
    public function like_answer(Request $request)
    {
        $userId         = $request->input('userId');
        $answerId       = $request->input('answerId');
        $questionModel  = new QuestionModel();
        $questionModel->add_or_cancel_like($userId,$answerId);
        return apiData()->send(200,'ok');
    }
}